package com.org.any.autocar.receiver;

import static com.autocar.reader.manager.URLManager.ARTILCE_URL;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;

import com.autocar.reader.bean.ChatListBean;
import com.autocar.reader.bean.NewsBean;
import com.autocar.reader.bean.XiaoxiBean;
import com.autocar.reader.util.ConstantData;
import com.autocar.reader.util.FileHandler;
import com.autocar.reader.util.PreferencesUtil;
import com.org.any.autocar.ChatListActivity;
import com.org.any.autocar.ReadContentActivity;
import com.org.any.autocar.fragment.ChatFragment;

/**
 */
public class MyReceiver extends BroadcastReceiver {
	private static final String TAG = "MyReceiver";

	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle bundle = intent.getExtras();
		Log.d(TAG, "onReceive - " + intent.getAction() + ", extras: "
				+ printBundle(bundle));
		if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {

			Log.i("test", "ACTION_REGISTRATION_ID");
		} else if (JPushInterface.ACTION_UNREGISTER.equals(intent.getAction())) {

			Log.i("test", "ACTION_UNREGISTER");
		} else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent
				.getAction())) {

			Log.i("test", "ACTION_MESSAGE_RECEIVED" + 3);

		} else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent
				.getAction())) {

			Log.i("test", "ACTION_NOTIFICATION_RECEIVED");
			// 接受到服务器数据
			int type = getType(bundle);
			XiaoxiBean xiaoxiBean = null;
			switch (type) {
			case 3:// 聊天推送
				xiaoxiBean = toChat(context, bundle);
				//
				break;
			case 1:// 商机提醒
				xiaoxiBean = getWarnChat(bundle);
				break;
			case 2:// 添加提醒
				xiaoxiBean = getRequestChat(bundle);
				break;
			case 4:
				xiaoxiBean = getSpaceChat(bundle);
				break;
			}
			xiaoxiBean.setType(type);
			refreshChat(xiaoxiBean, context);
		} else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent
				.getAction())) {
			Log.d(TAG, "jpush sdk");
			String msg[] = getData(bundle);
			if (msg != null)
				openReadContent(context, msg[0], msg[1], msg[2], msg[3]);
		} else {
			Log.d(TAG, "Unhandled intent - " + intent.getAction());
		}
	}

	public static void refreshChat(XiaoxiBean xiaoxiBean, Context context) {
		FileHandler fh = new FileHandler();
		List<XiaoxiBean> rlist = (List<XiaoxiBean>) fh.getObj(ConstantData
				.getUserChat("xiaoxiinfo"));
		if (rlist == null) {
			rlist = new ArrayList<XiaoxiBean>();
		}
		if (rlist.size() > 0) {
			int index = -1;
			for (int i = 0; i < rlist.size(); i++) {
				XiaoxiBean bean2 = rlist.get(i);
				Log.i("test", ""+bean2.getUid()+" "+xiaoxiBean.getUid()+" "+(bean2.getUid().equals(xiaoxiBean.getUid())));
				if (bean2.getUid().equals(xiaoxiBean.getUid())
						&& bean2.getType() == xiaoxiBean.getType()) {
					index = i;
					break;
				}
			}
			if (index != -1) {
				XiaoxiBean bean3 = rlist.remove(index);
				if(xiaoxiBean.getContent() == null || xiaoxiBean.getContent().length() < 1){
					xiaoxiBean.setContent(bean3.getContent());
				}
				if (rlist.size() > 0) {
					rlist.add(0, xiaoxiBean);
				} else {
					rlist.add(xiaoxiBean);
				}
			} else {
				rlist.add(0, xiaoxiBean);
			}
		} else {
			rlist.add(xiaoxiBean);
		}
		fh.saveObj(rlist, ConstantData.getUserChat("xiaoxiinfo"));
		Intent intent3 = new Intent(ChatFragment.BTAG);
		intent3.putExtra("type", 1);
		context.sendBroadcast(intent3);
	}

	public XiaoxiBean toChat(Context context, Bundle bundle) {
		FileHandler fh = new FileHandler();
		ChatListBean s = getUserChat2(bundle);
		List<ChatListBean> clist = (List<ChatListBean>) fh.getObj(ConstantData
				.getUserChat(s.getUid()));
		if (clist == null) {
			clist = new ArrayList<ChatListBean>();
		}
		clist.add(s);
		Log.i("test", "clist " + clist.size());
		fh.saveObj(clist, ConstantData.getUserChat(s.getUid()));

		// 閫氱煡鐣岄潰鍒锋柊
		Intent intent2 = new Intent(ChatListActivity.RTAG);
		context.sendBroadcast(intent2);

		XiaoxiBean bean = new XiaoxiBean();
		bean.setContent(s.getContent());
		bean.setUid(s.getUid());
		bean.setUsername(s.getUsername());
		bean.setPhoto(s.getPhone());
		bean.setAddtime(s.getAddtime());
		return bean;
	}

	private static String printBundle(Bundle bundle) {
		StringBuilder sb = new StringBuilder();
		for (String key : bundle.keySet()) {
			if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
				sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
			} else {
				sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
			}
		}
		return sb.toString();
	}

	public String[] getData(Bundle bundle) {
		try {
			String[] msg = new String[4];
			msg[1] = bundle.getString(JPushInterface.EXTRA_CONTENT_TYPE);
			msg[0] = bundle.getString(JPushInterface.EXTRA_EXTRA);
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject obj = new JSONObject(extras);
			JSONObject oobj = obj.optJSONObject("info");
			int type = oobj.optInt("type", -1);
			if (type == 6) {
				msg[2] = oobj.optString("cid");
				msg[3] = oobj.optString("id");
			}
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public int getType(Bundle bundle) {
		try {
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject obj = new JSONObject(extras);
			JSONObject oobj = obj.optJSONObject("info");
			int type = oobj.optInt("type", -1);
			return type;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

	public XiaoxiBean getUserChat(Bundle bundle) {
		try {
			XiaoxiBean bean = new XiaoxiBean();
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject obj = new JSONObject(extras);
			JSONObject oobj = obj.optJSONObject("info");
			bean.setUid(oobj.optString("uid"));
			bean.setContent(oobj.optString("content"));
			bean.setAddtime(oobj.optString("addtime"));
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public ChatListBean getUserChat2(Bundle bundle) {
		try {
			ChatListBean bean = new ChatListBean();
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject obj = new JSONObject(extras);
			JSONObject oobj = obj.optJSONObject("info");
			bean.setUid(oobj.optString("uid"));
			bean.setUsername(oobj.optString("uname"));
			bean.setPhone(oobj.optString("photo"));
			bean.setContent(oobj.optString("content"));
			bean.setAddtime(oobj.optString("addtime"));
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public XiaoxiBean getWarnChat(Bundle bundle) {
		try {
			XiaoxiBean bean = new XiaoxiBean();
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject obj = new JSONObject(extras);
			JSONObject oobj = obj.optJSONObject("info");
			bean.setUid(oobj.optString("uid"));
			bean.setId(oobj.optString("id"));
			bean.setContent(oobj.optString("comment"));
			bean.setPhoto(oobj.optString("photo"));
			bean.setUsername(oobj.optString("uname"));
			bean.setAddtime(oobj.optString("addtime"));
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public XiaoxiBean getRequestChat(Bundle bundle) {
		try {
			XiaoxiBean bean = new XiaoxiBean();
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject obj = new JSONObject(extras);
			JSONObject oobj = obj.optJSONObject("info");
			bean.setUid(oobj.optString("uid"));
			bean.setPhoto(oobj.optString("photo"));
			bean.setUsername(oobj.optString("uname"));
			bean.setAddtime(oobj.optString("addtime"));
			bean.setContent(oobj.optString("msg"));
			Log.i("test", oobj.optString("msg"));
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public XiaoxiBean getSpaceChat(Bundle bundle) {
		try {
			XiaoxiBean bean = new XiaoxiBean();
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			JSONObject obj = new JSONObject(extras);
			JSONObject oobj = obj.optJSONObject("info");
			bean.setUid(oobj.optString("uid"));
			bean.setPhoto(oobj.optString("photo"));
			bean.setUsername(oobj.optString("uname"));
			bean.setAddtime(oobj.optString("addtime"));
			bean.setContent(oobj.optString("msg"));
			return bean;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void openReadContent(Context context, String title, String flag,
			String cid, String aid) {

		if (PreferencesUtil.getUserbean(context) == null) {
			return;
		}

		Intent appIntent = new Intent(context, ReadContentActivity.class);
		appIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_CLEAR_TOP);
		appIntent.putExtra("sid", cid);
		NewsBean bean = new NewsBean();
		bean.setFulldataurl(ARTILCE_URL + aid);
		bean.setCid(cid);
		appIntent.putExtra("bean", bean);
		context.startActivity(appIntent);
	}

}
